package com.gogowan.agroenterprise.newview;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.ChuKuDiatalBean;
import com.gogowan.agroenterprise.model.ChukuRequest;
import com.gogowan.agroenterprise.model.UserType;
import com.gogowan.agroenterprise.utils.INewAdapterClick;
import com.gogowan.agroenterprise.utils.ToastUtils;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.ChuKuDiatalAdapter;
import com.google.gson.reflect.TypeToken;
import com.ioid.utils.JsonUtils;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class ChuKuDetailActivity extends BaseActivity implements View.OnClickListener {

    private int usertype;
    private long userId;
    private String username;
    private Button btn_search;
    private SpringView springView;
    private int page=1;
    private int totalPage=10;
    private ProgressDialog progressDialog;
    private ChuKuDiatalAdapter ChanPinDiatalAdapter;
    private ListView mainlist;
    private List<ChuKuDiatalBean> chuKuDiatalBeans=new ArrayList<>();
    private Context  mContext;
    private int pageSize=20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_chu_ku_detail);
        mContext=this;
        initView();
        initValue();
        usertype = MyApplication.mSettings.getInt("usertype", 1);
        userId=MyApplication.mSettings.getLong("personid",0);
        username=MyApplication.mSettings.getString("username","");
    }
    /**
     * 初始化界面
     */
    private void initView() {
        View  out_storage_fh_btn = findViewById(R.id.out_storage_fh_btn);
        out_storage_fh_btn.setOnClickListener(view->finish());
//        btn_search = (Button) findViewById(R.id.btn_search);
//        btn_search.setOnClickListener(this);
        mainlist=findViewById(R.id.mainlist);
        springView=(SpringView)findViewById(R.id.main_Sv);
        springView.setFooter(new DefaultHeader(this));
        springView.setHeader(new DefaultHeader(this));
        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                page=1;
                initValue();
            }

            @Override
            public void onLoadmore() {
                page++;
//                if (totalPage>=page){
//                    initValue();
//                }else {
//                    springView.onFinishFreshAndLoad();
//                    showToast("没有更多数据了");
//                }
                initValue();
            }
        });
//        xMListViewAdapter = new NewInXMListViewAdapter(this, boxCodeList, 2);
        ChanPinDiatalAdapter = new ChuKuDiatalAdapter(ChuKuDetailActivity.this, chuKuDiatalBeans, new INewAdapterClick() {
            @Override
            public void onItemClick(View view, final int position) {
                Intent intent=new Intent(mContext,ChanPinDetailActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("bean",chuKuDiatalBeans.get(position));
                intent.putExtras(bundle);
                startActivity(intent);


            }
        });
        mainlist.setAdapter(ChanPinDiatalAdapter);

    }

    /**
     * 初始化数据
     */
    private void initValue() {
        progressDialog = ProgressDialog.show(this, getString(R.string.alert_title), getString(R.string.alert_message),
                true, false);
        ChukuRequest dealerRequest = new ChukuRequest();
        dealerRequest.setPage(page);
        dealerRequest.setLimit(pageSize);
        GetChuKuDetailListAsyn getDealerListAsyn = new GetChuKuDetailListAsyn();
        getDealerListAsyn.execute(dealerRequest);
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.btn_search){
            //搜索
            page=1;
            initValue();
        }
    }
    /**
     * 获取经销商的经销商列表
     *
     * @author tjh
     *
     */
    private class GetChuKuDetailListAsyn extends MyAsyncTask {
        @Override
        protected void onPostExecute(Object res) {
            Log.d("DONG",res.toString());
            progressDialog.dismiss();
            springView.onFinishFreshAndLoad();
            if (res == null || res.equals("")) {
                Toast.makeText(ChuKuDetailActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo = new JSONObject(res.toString());
                    if (jo.getInt("code") != 200) {
                        Toast.makeText(getApplicationContext(), jo.getString("msg"), Toast.LENGTH_LONG).show();
                        return;
                    }
                    int totle = jo.getJSONObject("data").getInt("total");
                    totalPage=totle/pageSize+(totle%pageSize==0?0:1);
                    res = jo.getJSONObject("data").getJSONArray("list");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (res == null || res.equals("")) {
                    Toast.makeText(ChuKuDetailActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
                            .show();
                } else {
                    Type userListType = new TypeToken<List<ChuKuDiatalBean>>() {
                    }.getType();
                    List<ChuKuDiatalBean> storeListResult = (List<ChuKuDiatalBean>) JsonUtils.fromJSON(res.toString(), userListType);
                    if(page==1){
                        chuKuDiatalBeans.clear();
                    }
                    if (storeListResult != null && storeListResult.size() > 0) {

                        chuKuDiatalBeans.addAll(storeListResult);
                        myHandler.sendEmptyMessage(1);
                    } else {
                        if(page==1){
                            ToastUtils.show(mContext,"暂无数据！");
                        }else{
                            ToastUtils.show(mContext,"没有更多数据了！");
                        }
                        myHandler.sendEmptyMessage(1);
                    }
                }
            }
//            progressDialog.dismiss();
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            ChukuRequest outStorageRequest = (ChukuRequest) params[0];
            String url=getString(R.string.first_url) +
                    getString(R.string.getOutboundInfoList) +"?"+
//                    "?number=" + btn_search.getText().toString()+
//                    "&batchOrCode"+btn_search.getText().toString()+
//                    "?personid="+userId+
//                    "?number=" + outStorageRequest.getNumber()+
                    "page="+outStorageRequest.getPage()+
                    "&limit="+outStorageRequest.getLimit();

            Log.d("DONG",url);
            String res = Utils.getCommit(url);
            Log.d("DONG",url+res);
            return res;
        }
    }
    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://经销商
                    ChanPinDiatalAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };
}